import 'dart:convert';
import 'dart:io';
// import 'package:lib_runtime/lib_runtime.dart';
// import 'package:lib_user/lib_user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path/path.dart';

import '../../lib_runtime/global_config.dart';
import '../../lib_runtime/logger.dart';
import '../../lib_runtime/utils/num_util.dart';
import '../../lib_user/user_manager.dart';

late SharedPreferences _prefs;

class CacheKeys {
  CacheKeys._();

  static const userCacheKey = 'userCacheKey';
  static const languageCode = "language_code"; // 新增

  static const giftCacheKey = 'giftCacheKey';

  ///缓存礼物数据

  ///ser index
  static const serEnv = '_jr_.ser.env';

  static const carListCacheKey = 'carListCacheKey';

  ///缓存的车辆排行榜数据

  ///缓存表情
  static String emoteListCacheKey(String id) {
    return 'emoteListCacheKey_$id';
  }

  ///缓存表情tab
  static String emoteTabCacheKey(String scene) {
    return 'emoteListCacheKey_$scene';
  }

  ///记录用户首次进入首页
  static String get userHasEnterHomePageKey =>
      'userHasEnterHomePageKey_${UserManager.instance.currentUid}';

  static String get lastLoadConvFromServer =>
      '${UserManager.instance.currentUid}.last.conv.server';

  static const hasClearTransactionReceipt = 'hasClearTransactionReceipt';
  static const lastLoginPhone = 'lastLoginPhone';
  static const lastLoginAreaCode = 'lastLoginAreaCode';
  static const lastLoginEmail = 'lastLoginEmail';
  static const lastSendEmailCodeTime = 'lastSendEmailCodeTime';
  static String get userHasShowHomeRedPageKey =>
      'userHasShowHomeRedPageKey_${UserManager.instance.currentUid}';

  ///亲密度动画缓存
  static String intimacyUpgradeCacheKey(String tid) {
    return 'intimacyUpgradeCacheKey_$tid';
  }

  /// 用户登录次数缓存key
  static String userLoginCountCacheKey(String id) {
    return 'userLoginCountCacheKey_$id';
  }
}

class CacheUtilAction {
  ///更新加入房间的时间
  static updateJoinRoomTime(int rid) {
    int time = DateTime.now().millisecondsSinceEpoch;
    CacheUtil.setInt('lastTimeJoinRoomKey_$rid', time);
  }

  ///加入房间是否需要显示弹出公告
  static bool joinRoomNeedShowNotice(int rid) {
    int time = CacheUtil.getInt('lastTimeJoinRoomKey_$rid');
    int nowTime = DateTime.now().millisecondsSinceEpoch;
    return (nowTime - time) > 1000 * 60 * 10;
  }
}

class CacheUtil {
  CacheUtil._();

  static init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// 存储
  static saveObject(String key, Object? value) async {
    if (value != null) {
      String obj = json.encode(value);
      _prefs.setString(key, obj);
    }
  }

  /// 获取存储数据
  static getObject(String key) async {
    String? value = _prefs.getString(key);
    if (value != null) {
      return json.decode(value);
    }
  }

  /// 移除存储数据
  static Future<bool> removeObject(String key) => _prefs.remove(key);

  /// 全部清空
  static clear() async {
    _prefs.clear();
  }

  static Future<bool> set(String key, String value) {
    return _prefs.setString(key, value);
  }

  static String get(String key, [String defaultValue = '']) {
    String? res = _prefs.getString(key);
    return res ?? defaultValue;
  }

  static int getInt(String key, [int defaultValue = 0]) {
    return _prefs.getInt(key) ?? defaultValue;
  }

  static Future<bool> setInt(String key, int value) {
    return _prefs.setInt(key, NumUtil.parseInt(value));
  }

  static Future<bool> setBool(String key, bool value) {
    return _prefs.setBool(key, value);
  }

  static bool getBool(String key, [bool defaultValue = false]) {
    bool? value = _prefs.getBool(key);
    return value ?? defaultValue;
  }

  static delete(String key) {
    _prefs.remove(key);
  }

  static Future<bool> saveBean(String key, dynamic data) async {
    try {
      File file = File(
          join(GlobalConfig.instance.appDirectory.path, 'bean_cache', key));
      if (!file.existsSync()) {
        await file.create(recursive: true);
      }
      file.writeAsString(json.encode(data));
      return true;
    } catch (e) {
      RLog.d('saveBean == $e');
    }
    return false;
  }

  static Future<T?>? getBean<T>(String key) async {
    try {
      File file = File(
          join(GlobalConfig.instance.appDirectory.path, 'bean_cache', key));
      if (!file.existsSync()) {
        return null;
      }
      String json = file.readAsStringSync();
      return jsonDecode(json);
    } catch (e) {
      RLog.d('getBean == $e');
    }
    return null;
  }
}
